# -*- coding: utf-8 -*
import re
import subprocess

from ..common import Collector


class LoadCollector(Collector):
    """cpu 平均负载收集器： 收集近1，5,15分钟的load average指标"""
    def __init__(self, is_test):
        super().__init__(is_test)
        self.time_hashtable = {
            "1": 0.0,
            "5": 0.0,
            "15": 0.0
        }

    def get_metric(self, time: str) -> float:
        """获取某一段时间的load"""
        return self.time_hashtable[time]

    def collect(self) -> None:
        if self.is_test:
            test_file_path = Collector.get_test_file_path("uptime.txt", __file__)
            with open(test_file_path, "r", encoding="utf-8") as f:
                lines = f.readlines()
                out_str = lines[-1]
        else:
            process_out = subprocess.run(["uptime"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            out_str = str(process_out.stdout, encoding="utf-8")
            
        pat = re.compile(r"\s+")
        load_str = pat.sub("", out_str)[-14:]  # 0.00,0.00,0.00
        load_list = load_str.split(",")
        load_list = list(map(float, load_list))
        self.time_hashtable["1"] = load_list[0]
        self.time_hashtable["5"] = load_list[1]
        self.time_hashtable["15"] = load_list[2]
        self.stash.extend(load_list)
